package com.xyf.sys.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.xyf.sys.vo.OrderPayment;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
public class CsvGenerator {

    public static String generateCsv(String tempDir, String startDate, String endDate, List<OrderPayment> list, String deptName, BigDecimal totalPayment, BigDecimal deliveryAmount, BigDecimal laundryAmount, boolean supplier) {
        // 创建目录
        String dir = tempDir + "/" + "收款记录" + "/";
        File file = new File(dir);
        file.mkdirs();
        // 创建文件路径
        String filePath = dir + deptName + "收款记录明细" + IdUtil.getSnowflakeNextIdStr() + ".csv";
        // 生成 sheetName
        String sheetName = "";
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            sheetName = startDate + "-" + endDate;
        }
        // 生成 CSV 文件
        // 生成 CSV 文件
        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8))) {
            // 写入 BOM 标记
            writer.write('\uFEFF');
            if (!supplier) {
                // 写入总计行
                writer.println(deptName + ",合计金额:," + totalPayment.setScale(2, RoundingMode.HALF_UP).toPlainString() + ",快递金额:, " + deliveryAmount + ",干洗金额:, " + laundryAmount + ",,,,,,,,,,,,,,,");
                // 写入空行
                writer.println(",,,,,,,,,,,,,,,,,,,,,");
                // 写入表头
                writer.println("姓名,付款人,用户(下单人),订单类型,日期,退款日期,打单重量,结算重量,重量差,金额,超重金额,团长利润,利润公式,价格方案,订单号,快递公司,物流单号,邮寄物品,发往,说明,收件人电话,收件人地址");
                // 写入数据行
                for (OrderPayment payment : list) {
                    writer.println(
                            payment.getName() + "," +
                                    payment.getPayerName() + "," +
                                    (payment.getUserName() == null ? "" : "`" + payment.getUserName())  + "," +
                                    payment.getOrderTypeFormat() + "," +
                                    (payment.getPaymentDate() == null ? "" : payment.getPaymentDate()) + "," +
                                    (payment.getRefundTime() == null ? "" : DateUtil.format(payment.getRefundTime(), "yyyy-MM-dd HH:mm:ss")) + "," +
                                    (payment.getWeight() == null ? "" : payment.getWeight()) + "," +
                                    (payment.getSettleWeight() == null ? "" : payment.getSettleWeight()) + "," +
                                    (payment.getWeightDiff() == null ? "" : payment.getWeightDiff()) + "," +
                                    payment.getAmount().toPlainString() + "," +
                                    (payment.getOverWeightAmount() == null ? "" : payment.getOverWeightAmount().toPlainString()) + "," +
                                    (payment.getRegimentProfit() == null ? BigDecimal.ZERO.toPlainString() : payment.getRegimentProfit().setScale(2, RoundingMode.HALF_UP).toPlainString()) + "," +
                                    (payment.getProfitFormula() == null ? "" : payment.getProfitFormula()) + "," +
                                    (payment.getLogisticPriceSchemeId() == null ? "" : payment.getLogisticPriceSchemeId().toString()) + "," +
                                    "`" + payment.getOrderId() + "," +
                                    (payment.getDeliveryName() == null ? "" : payment.getDeliveryName()) + "," +
                                    (payment.getWaybillId() == null ? "" : payment.getWaybillId()) + "," +
                                    payment.getBusinessDescription() + "," +
                                    (payment.getReceiverProvince() == null ? "" : payment.getReceiverProvince()) + "," +
                                    (payment.getNote() == null ? "" : payment.getNote()) + "," +
                                    (payment.getReceiverMobile() == null ? "" : "`" +payment.getReceiverMobile()) + "," +
                                    (payment.getReceiverAddress() == null ? "" : payment.getReceiverAddress())
                    );
                }
            } else {
                // 写入表头
                writer.println(deptName + ",总计:," + totalPayment.setScale(2, RoundingMode.HALF_UP).toPlainString() + ",,,,,,,,,,,,,,");
                // 写入空行
                writer.println(",,,,,,,,,,,,");
                // 写入总计行
                writer.println("站点, 付款人,用户(下单人),订单类型,日期,退款日期,金额,工厂利润,利润公式,价格方案,订单号,品名*数量,说明");
                // 写入数据行
                for (OrderPayment payment : list) {
                    writer.println(
                            payment.getName() + "," +
                                    payment.getPayerName() + "," +
                                    payment.getUserName() + "," +
                                    payment.getOrderTypeFormat() + "," +
                                    (payment.getPaymentDate() == null ? "" : payment.getPaymentDate()) + "," +
                                    (payment.getRefundTime() == null ? "" : DateUtil.format(payment.getRefundTime(), "yyyy-MM-dd HH:mm:ss")) + "," +
                                    payment.getAmount().toPlainString() + "," +
                                    (payment.getRegimentProfit() == null ? BigDecimal.ZERO.toPlainString() : payment.getRegimentProfit().setScale(2, RoundingMode.HALF_UP).toPlainString()) + "," +
                                    (payment.getProfitFormula() == null ? "" : payment.getProfitFormula()) + "," +
                                    (payment.getLogisticPriceSchemeId() == null ? "" : payment.getLogisticPriceSchemeId().toString()) + "," +
                                    payment.getOrderId() + "," +
                                    payment.getBusinessDescription() + "," +
                                    (payment.getNote() == null ? "" : payment.getNote())
                    );
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成 CSV 文件失败: {}", e);
        }
        return filePath;
    }


    public static String generateOrderExportCsv(String tempDir, String startDate, String endDate, List<OrderPayment> list, String deptName) {
        // 创建目录
        String dir = tempDir + "/" + "订单" + "/";
        File file = new File(dir);
        file.mkdirs();
        // 创建文件路径
        String filePath = dir + deptName + "订单记录明细" + IdUtil.getSnowflakeNextIdStr() + ".csv";
        // 生成 sheetName
        String sheetName = "";
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            sheetName = startDate + "-" + endDate;
        }
        // 生成 CSV 文件
        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8))) {
            // 写入 BOM 标记
            writer.write('\uFEFF');
            // 写入表头
            writer.println("团主,团长,用户名/用户手机号,商品名称,收货人姓名,收货人电话,收货地址,订单金额, 订单id, 下单时间,支付时间,退款时间");
            // 写入数据行
            for (OrderPayment payment : list) {
                writer.println(
                                payment.getOwnerName() + "," +
                                (payment.getDeptName() == null ? "" : payment.getDeptName()) + "," +
                                (payment.getUserName() == null ? "" : payment.getUserName()) + "," +
                                (payment.getBusinessDescription() == null ? "" : payment.getBusinessDescription()) + "," +
                                (payment.getReceiverName() == null ? "" : payment.getReceiverName()) + "," +
                                (payment.getReceiverMobile() == null ? "" : payment.getReceiverMobile()) + "," +
                                (payment.getReceiverAddress() == null ? "" : "\"" + payment.getReceiverAddress()) + "\"" + "," +
                                (payment.getAmount() == null ? "" : payment.getAmount().toPlainString()) + "," +
                                (payment.getOrderId() == null ? "" : "\"" +  payment.getOrderId()) + "\"" + "," +
                                (payment.getOrderTime() == null ? "" : DateUtil.format(payment.getOrderTime(), "yyyy-MM-dd HH:mm:ss")) + "," +
                                (payment.getPaymentDate() == null ? "" : payment.getPaymentDate()) + "," +
                                (payment.getRefundTime() == null ? "" : DateUtil.format(payment.getRefundTime(), "yyyy-MM-dd HH:mm:ss"))
                );
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成 CSV 文件失败: {}", e);
        }
        return filePath;
    }
}